﻿#include "stdafx.h"
#include "MergeTrees.h"

using namespace std;

namespace algorithm {
	TreeNode* CMergeTrees::Merge(TreeNode* root1, TreeNode* root2)
	{
		if (!root1 && !root2) {
			return nullptr;
		}
		else if (!root1) {
			TreeNode* newNode = new TreeNode(root2->val);
			newNode->left = Merge(nullptr, root2->left);
			newNode->right = Merge(nullptr, root2->right);
			return newNode;
		}
		else if (!root2) {
			TreeNode* newNode = new TreeNode(root1->val);
			newNode->left = Merge(root1->left, nullptr);
			newNode->right = Merge(root1->right, nullptr);
			return newNode;
		}
		TreeNode* newNode = new TreeNode(root1->val + root2->val);
		newNode->left = Merge(root1->left, root2->left);
		newNode->right = Merge(root1->right, root2->right);

		return newNode;
	}
}
